import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:todo_app/components/Button/CustomIconButton.dart';
import 'package:todo_app/components/FontIcon.dart';
import 'package:todo_app/components/Overlay/main.dart';
import 'package:todo_app/components/TextExt.dart';
import 'package:todo_app/constants/DColor.dart';
import 'package:todo_app/controllers/TodoController.dart';
import 'package:todo_app/controllers/definitions/IdsParams.dart';
import 'package:todo_app/controllers/definitions/TodoModel.dart';
import 'package:todo_app/hooks/Throttle.dart';
import 'package:todo_app/layout/CustomCard.dart';
import 'package:todo_app/layout/Gaps.dart';
import 'package:todo_app/layout/Header.dart';
import 'package:todo_app/layout/ListItem.dart';
import 'package:todo_app/utils/AlarmClock.dart';
import 'package:todo_app/utils/ExtHelper.dart';


class TodoDetailPage extends HookWidget {
  const TodoDetailPage({Key? key, required this.id }) : super(key: key);
  final String id;

  @override
  Widget build(BuildContext context) {
    var todo = useState<TodoModel?>(null);
    var refreshKey = useState<int>(0);
    var checked = useState(false);
    var throttle = useThrottle<int>((int _) {
      if(todo.value?.id == null) return;
      var todoId = todo.value!.id!;
      var params = IdsParams()..ids=[todoId];
      if(todo.value?.is_collect != 1) {
        TodoController.collectUsingPost(params).then((res) {
          if(res.status == 'success') {
            refreshKey.value += 1;
            showOverlayToast("收藏成功");
          } else {
            showOverlayToast("收藏失败");
          }
        });
      } else {
        TodoController.cancelCollectUsingPost(params).then((res) {
          if(res.status == 'success') {
            refreshKey.value -= 1;
            showOverlayToast("取消收藏成功");
          } else {
            showOverlayToast("取消收藏失败");
          }
        });
      }
    }, duration: const Duration(milliseconds: 250), initialValue: 0);

    useEffect(() {
      var flag = todo.value != null && todo.value!.alert != null && AlarmClock.exist(todo.value!.alert!.id!);
      checked.value = flag;
      return () {};
    }, [todo.value, refreshKey.value]);

    useEffect(() {
      TodoController.detailUsingGet(id).then((res) {
        todo.value = res.data;
      });
      return () {};
    }, [refreshKey.value]);

    var checkedChange = useCallback(() async {
      if(todo.value == null) return;
      if(todo.value!.alert == null) return;
      var alertId = todo.value!.alert!.id!;
      if(todo.value!.alertTime != null && checked.value) {
        await AlarmClock.set(todo.value!.alertTime!, alertId, title: todo.value?.title, description: todo.value?.content);
        refreshKey.value = todo.value!.alertTime!.millisecondsSinceEpoch;
      }
      if(checked.value == false) {
        await AlarmClock.cancel(alertId);
        refreshKey.value = 0;
      }
    }, [checked.value]);

    return Scaffold(
      appBar: const Header(title: '待办事项详情',),
      body: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CustomCard(
              margin: EdgeInsets.only(
                top: 15.dp
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  ListItem(title: TextExt.title("标题"), height: 44.dp, border: true, content: ListItem.buildContent(TextExt.desc(todo.value?.title ?? "")),),
                  ListItem(title: TextExt.title("说明"), height: 44.dp, border: true, content: Container(
                    width: 300.dp,
                    alignment: Alignment.centerRight,
                    child: TextExt.desc(
                      todo.value?.content ?? "", 
                      maxLines: 4, 
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.left
                    )
                  ),),
                  ListItem(title: TextExt.title("所属分组"), height: 44.dp, content: ListItem.buildContent(TextExt.desc(todo.value?.group?.group_name ?? "-")),),
                ],
              )
            ),
            CustomCard(
              margin: EdgeInsets.only(
                top: 15.dp
              ),
              child: Column(
                children: [
                  ListItem(title: TextExt.title("是否农历"), height: 44.dp, border: true, content: ListItem.buildContent(TextExt.desc(todo.value?.alert?.lunar == true ? '是' : '否'))),
                  ListItem(title: TextExt.title("提醒类型"), height: 44.dp, border: true, content: ListItem.buildContent(TextExt.desc(todo.value?.alert?.alert_type == 'LOOP' ? '循环提醒' : '单次提醒'))),
                  ListItem(title: TextExt.title("开始时间"), height: 44.dp, border: true, content: ListItem.buildContent(TextExt.desc(todo.value?.alert?.alert_time.toDateTime().toYMDHm("-") ?? "-"))),
                  ListItem(title: TextExt.title("最近提醒时间"), height: 44.dp, border: true, content: ListItem.buildContent(TextExt.desc(todo.value?.alert?.last_alert_time.toDateTime().toYMDHm("-") ?? "-"),)),
                  ListItem(title: TextExt.title("下次提醒时间"), height: 44.dp, content: ListItem.buildContent(TextExt.desc(todo.value?.alertTime.toYMDHm('-') ?? "", style: const TextStyle(color: DColor.primary))),)
                ],
              )
            ),
            CustomCard(
              margin: EdgeInsets.only(
                top: 15.dp
              ),
              child: Column(
                children: [
                  ListItem(
                    onTap: () async {
                      var flag = todo.value != null && todo.value!.alert != null && AlarmClock.exist(todo.value!.alert!.id!);
                      checked.value = !flag;
                      checkedChange();
                    },
                    title: TextExt.title("闹钟"), 
                    padding: EdgeInsets.only(left: 15.dp),
                    content: ListItem.buildContent(Switch(
                      activeColor: DColor.primary,
                      value: checked.value, 
                      onChanged: (falg) {
                        checked.value = falg;
                        checkedChange();
                      }
                    ),)
                  ),
                ],
              )
            ),
            Container(
              margin: EdgeInsets.symmetric(vertical: 12.dp),
              alignment: Alignment.center,
              child: CustomIconButton(
                spacing: 6.dp,
                onTap: () {
                  throttle.setValue(throttle.value + 1);
                },
                direction: Axis.horizontal,
                icon: FontIcon(
                  icon: todo.value?.is_collect == 1 ? FontIcons.starFull : FontIcons.starEmpty, 
                  color: todo.value?.is_collect == 1 ? DColor.primary : DColor.gray,
                  size: 16.dp,
                ),
                child: Text(
                  todo.value?.is_collect == 1 ?  "已收藏" : "收藏", 
                  style: TextStyle(color: todo.value?.is_collect == 1 ? DColor.primary : DColor.gray, fontSize: 14.dp, height: 1),
                ),
              )
            )
          ],
        ),
      ),
    );
  }
}